<template>
  <div class="reset-password" v-loading.fullscreen.lock="loading">
    <template v-if="passwordData!==null">
      <el-form label-width="auto" size="medium">
        <el-form-item label="用户名">
          <el-input v-model="passwordData.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="passwordData.userPhone"></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordData.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="passwordData.confirmPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input style="width:calc(100% - 118px)" v-model="passwordData.phoneCode"></el-input>
          <countdown-button text="获取验证码" actionText="重新获取" size="medium" width="112px" type="primary" :count="60"
            :before-click-fun="getVerificationCode">
          </countdown-button>
        </el-form-item>
      </el-form>

      <div style="text-align:center">
        <el-button size="medium" type="primary" @click="update">重新设置新密码</el-button>
      </div>
    </template>
  </div>
</template>

<script>
  import LoginPassword from 'models/login/loginPassword';

  import CommonApi from 'services/commonApi';
  import LoginApi from 'services/loginApi';

  import CountdownButton from 'commonComponents/countdownButton';

  export default {
    data() {
      return {
        loading: false,
        passwordData: new LoginPassword()
      };
    },

    methods: {
      getVerificationCode() {
        let passwordData = this.passwordData;
        let userPhone = passwordData.userPhone;
        if (userPhone === null || userPhone.trim() === '') {
          this.$message('没有设置手机号，不能修改密码');
          return Promise.reject();
        }

        return CommonApi.sendVerificationCode(userPhone, false).then(() => {
          this.$message('验证码发送成功，有效期5分钟');
          return true;
        }).catch(() => {
          return false;
        });
      },

      update() {
        let passwordData = this.passwordData;
        let code = passwordData.checkValid();
        if (code !== '') {
          let msg = this.i18n.getMsg(`login.error.resetPwd.${code}`);
          this.$message(msg);
          return;
        }

        this.loading = true;
        LoginApi.resetPassword(passwordData).then(() => {
          this.loading = false;
          this.$alert('新密码设置成功，可以使用新密码登录', '信息', {
            callback: () => {
              this.$emit('reset-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      }
    },

    components: {
      CountdownButton
    }
  };

</script>

<style lang="scss" scoped>
  .reset-password {
    padding: 0 10px 5px;

    .el-form-item {
      margin-bottom: 10px;
    }
  }

</style>
